package com.jee.ssm.common.rabbitMQ;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jee.ssm.common.utils.UUIDFactory;
import com.jee.ssm.model.Handheld;
import com.jee.ssm.modules.handheld.services.HandheldService;
import com.rabbitmq.client.Channel;

import org.apache.log4j.Logger;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.Date;


/**
 * rabbitmq
 * 消费者
 * zsj
 */
public class Consumor implements ChannelAwareMessageListener {

    private Logger logger = Logger.getLogger(Consumor.class);

    public void logInfo(String msg){
        logger.info("RabbitMQ(mq.server.send):" + msg);
    }
    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        logInfo("消费者接收到信息");
        String msg = new String(message.getBody(), StandardCharsets.UTF_8);
        //消息的标识，false只确认当前一个消息收到，true确认所有consumer获得的消息
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        //ack返回false，并重新回到队列，api里面解释得很清楚
        //channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
        //true拒绝消息 false确认接受到消息
        //channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
        logInfo("消费者消费掉了消息:" + msg);
        try {
            JSONObject jsonObject = JSON.parseObject(msg);
            String code = jsonObject.getString("number");//编号
            String lng = jsonObject.getString("longitude");//经度
            String lat = jsonObject.getString("latitude");//纬度
            String battery = jsonObject.getString("battery");//电量
            String userId = jsonObject.getString("userId");//登录用户

            if (userId.equals("userId")){
                //userId = "";
                return;
            }
            updateHandheld(code,lng,lat,battery,userId);
        }catch (Exception e){
            logInfo("消息不是json格式"+msg);
        }

    }


    /**
     * 添加/更新手持机信息
     * @param code 编号
     * @param lng 经度
     * @param lat 维度
     * @param battery 电量
     */
    public void updateHandheld(String code,String lng,String lat,String battery,String userId){
        Handheld handheld = handheldService.selectByNumber(code);
        try {
            if (handheld != null){
                logInfo("手持机存在，更改信息。");
                Handheld h = new Handheld(handheld.getId(),1,lng,lat,battery,new Date(),userId);
                handheldService.updateById(h);
            }else{
                logInfo("手持机不存在，添加手持机：" + code);
                Handheld h = new Handheld(UUIDFactory.getStringId(),code,1,lng,lat,battery,0,new Date(),new Date(),userId);
                handheldService.insert(h);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Resource
    private HandheldService handheldService;

}
